﻿using AutoMapper;
using Benefactor.Models.DtoModels;
using Benefactor.Services;
using Benefactor.Services.Repositories;
using Bigway.Common.Models.DtoModels;
using Microsoft.AspNetCore.Mvc;

namespace Benefactor.Controllers;

using static Errors;

[ApiController]
[Route("api/benefits_card_order")]
public class BenefitsCardOrderController(
        IBenefitsCardOrderRepository benefitsCardOrderRepository,
        IAppConfig appConfig,
        IMapper mapper,
        ILogger<BenefitsCardOrderController> logger): ControllerBase
{
    [HttpGet]
    public async Task<GetBenefitsCardOrdersResponseDto> GetBenefitsCardOrdersAsync(
        [FromQuery(Name = "api_key")] string apiKey,
        [FromQuery] GetBenefitsCardOrdersRequestDto request,
        CancellationToken token = default)
    {
        if (apiKey != appConfig.ApiKey)
            return Unauthorized<GetBenefitsCardOrdersResponseDto>();

        var systemId = request.system_id;
        var buyerAccount = request.buyer_account;
        var benefitsCardId = request.benefits_card_id;
        var benefitsCardOrderId = request.benefits_card_order_id;
        logger.LogInformation("Getting benefits card orders...");

        var benefitsCardOrders = await benefitsCardOrderRepository.GetAllAsync(
            query =>
            {
                query = query.Where(x => !x.IsDeleted && x.SystemId == systemId);
                
                if (!string.IsNullOrEmpty(benefitsCardId))
                    query = query.Where(x => x.BenefitsCardId == benefitsCardId);

                if (!string.IsNullOrEmpty(benefitsCardOrderId))
                    query = query.Where(x => x.Id == benefitsCardOrderId);

                if (!string.IsNullOrEmpty(buyerAccount))
                    query = query.Where(x => x.BuyerAccount == buyerAccount);

                query = query.OrderByDescending(x => x.CreateTime);

                return query;
            }, token);

        return new GetBenefitsCardOrdersResponseDto
        {
            Data = benefitsCardOrders
                .Select(mapper.Map<BenefitsCardOrderInfo>)
        };
    }
}